﻿using AlipayPay.Infrastructure.Api;
using AlipayPay.Infrastructure.EntitiyExtensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AlipayPay.Api.Controllers.Common
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class BaseController : Controller
    {

        #region get请求返回json

        /// <summary>
        /// get请求返回json
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        protected new JsonResult Json(object data = null)
        {
            if (data == null)
            {
                data = new { };
            }

            var result = ApiResult.Success(data);
            return base.Json(result);
        }

        #endregion

        #region 通用提交（异步）

        /// <summary>
        /// 通用提交
        /// </summary>
        /// <param name="data">响应信息 可不填 可自定义</param>
        /// <returns></returns>
        protected async Task<JsonResult> CommitUofAndFormatMsgAsync(Func<object> data = null, Action successAction = null,
            Action failedAction = null)
        {
            var dbres = await Request.HttpContext.RequestServices.GetService<IUnitOfWork>().CommitAsync();
            return FormatMsg(dbres, data?.Invoke(), successAction, failedAction);
        }

        #endregion

        #region 格式化消息

        /// <summary>
        /// 格式化消息
        /// </summary>
        /// <param name="dbRes"></param>
        /// <param name="data"></param>
        /// <param name="successAction"></param>
        /// <param name="failedAction"></param>
        /// <returns></returns>
        protected JsonResult FormatMsg(bool dbRes, object data = null, Action successAction = null,
            Action failedAction = null)
        {
            if (dbRes)
            {
                successAction?.Invoke();
                return Json(data);
            }
            else
            {
                failedAction?.Invoke();
                return Json(data);
            }
        }

        #endregion

    }
}
